<template>
	<div v-if="pageType === 'i'" class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					label-width="auto"
				>
					<el-form-item
						:label="$t('common.belong_merchant') + ':'"
						prop="merchantId"
					>
						<merchant-select
							v-model="queryData.merchantId"
							:placeholder="$t('common.all')"
						></merchant-select>
					</el-form-item>
					<el-form-item prop="createdAt">
						<el-select
							v-model="selectSearchType"
							size="medium"
							style="width:130px"
						>
							<el-option
								:label="$t('common.createAt')"
								:value="1"
							></el-option>
							<el-option
								:label="$t('agent.last_modified_time')"
								:value="2"
							></el-option>
						</el-select>
						<el-date-picker
							v-model="selectSearchVal"
							size="medium"
							:picker-options="pickerShortcut2"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							clearable
							:default-time="defaultTime"
						></el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-input
							v-model="selectSearchVal2"
							clearable
							size="medium"
							:maxlength="12"
							:placeholder="$t('common.please_enter')"
						>
							<el-select
								slot="prepend"
								v-model="selectSearchType2"
								style="width: 120px"
								:placeholder="$t('common.please_choose')"
								@change="selectSearchType2Handle"
							>
								<el-option
									:label="$t('common.createBy')"
									:value="1"
								></el-option>
								<el-option
									:label="$t('agent.last_modified_people')"
									:value="2"
								></el-option>
							</el-select>
						</el-input>
					</el-form-item>
					<el-form-item
						:label="$t('agent.template_type') + ':'"
						prop="templateType"
					>
						<el-select
							v-model="queryData.templateType"
							style="width: 120px"
							clearable
							collapse-tags
							:placeholder="$t('common.all')"
							:popper-append-to-body="false"
							@change="getPolicyTypeOnSearchForm($event)"
						>
							<el-option
								v-for="item in templateTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.policy_type') + ':'">
						<el-select
							v-model="queryData.policyTypeConfigId"
							clearable
							collapse-tags
							:placeholder="$t('common.all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="item in typeConfigIdList"
								:key="item.id"
								:label="item.policyType"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('204011')"
							icon="el-icon-folder"
							type="warning"
							:disabled="loading"
							size="medium"
							@click="openDialog(false)"
						>
							{{ $t('agent.add') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="tableData"
					style="width: 100%"
					:header-cell-style="getRowClass"
					highlight-current-row
				>
					<el-table-column
						prop="merchantId"
						align="center"
						:label="$t('common.belong_merchant')"
						width="230"
					>
						<template slot-scope="scope">
							<span>
								{{ merchantFilter(scope.row.merchantId) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="policyTypeConfigId"
						align="center"
						:label="$t('agent.policy_type')"
					>
						<template slot-scope="scope">
							{{
								filterPolicyType(
									scope.row.policyTypeConfigId,
									scope.row.templateType
								)
							}}
						</template>
					</el-table-column>
					<el-table-column
						prop="templateName"
						align="center"
						:label="$t('agent.template_name')"
						width="200"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.templateName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="templateType"
						align="center"
						:label="$t('agent.template_type')"
						width="150"
					>
						<template slot-scope="scope">
							<span>
								{{ filterContractType(scope.row.templateType) }}
							</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="templateDes"
						align="center"
						:label="$t('agent.template_desc')"
						width="200"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.templateDes || '-' }}</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="createdBy"
						align="center"
						:label="$t('common.createBy')"
						width="130"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createdBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						:label="$t('common.createAt')"
						width="200"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createdAt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedBy"
						align="center"
						:label="$t('agent.last_modified_people')"
						width="130"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedAt"
						align="center"
						:label="$t('agent.last_modified_time')"
						width="200"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedAt || '-' }}</span>
						</template>
					</el-table-column>

					<el-table-column
						align="center"
						:label="$t('common.actions')"
						min-width="260"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="hasPermission('204015')"
								:disabled="loading"
								type="success"
								size="medium"
								class="noicon"
								@click="openSettings(scope.row)"
							>
								{{ $t('agent.setting_ratio') }}
							</el-button>

							<el-button
								v-if="hasPermission('204013')"
								type="primary"
								icon="el-icon-edit"
								:disabled="scope.row.status === 1"
								size="medium"
								@click="openDialog(true, scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="hasPermission('204012')"
								type="danger"
								icon="el-icon-delete"
								size="medium"
								:disabled="scope.row.status === 1"
								@click="del(scope.row, scope.$index)"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<el-dialog
					:title="dialog.title"
					:visible.sync="dialog.visible"
					width="500px"
					top="20vh"
					@closed="closeDialog"
				>
					<el-form
						ref="dialogForm"
						:model="dialog.formData"
						label-width="auto"
						size="normal"
						:rules="dialog.rules"
					>
						<el-form-item
							:label="$t('common.choose_merchant') + ':'"
							prop="merchantId"
						>
							<merchant-select
								v-model="dialog.formData.merchantId"
								style="width:80%"
								:placeholder="$t('common.please_choose')"
								:disabled="
									dialog.title === $t('common.edit') ||
										merchantList.length === 1
								"
								@change="selectMerchantHandle"
							></merchant-select>
						</el-form-item>
						<el-form-item
							:label="$t('agent.template_type') + ':'"
							prop="templateType"
						>
							<el-select
								v-model="dialog.formData.templateType"
								:placeholder="
									$t('agent.rule_select_tip_template')
								"
								:disabled="dialog.title === $t('common.edit')"
								style="width:80%"
								@change="getPolicyTypeInDialog($event)"
							>
								<el-option
									v-for="item in templateTypeArr"
									:key="item.code"
									:label="item.description"
									:value="item.code"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item
							:label="$t('agent.policy_type') + ':'"
							prop="policyTypeConfigId"
						>
							<el-select
								v-model="dialog.formData.policyTypeConfigId"
								style="width:80%"
								:disabled="dialog.title === $t('common.edit')"
								clearable
								:placeholder="$t('common.please_choose')"
							>
								<el-option
									v-for="item in dialogTypeConfigIdList"
									:key="item.id"
									:label="item.policyType"
									:value="item.id"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item
							:label="$t('agent.template_name') + ':'"
							prop="templateName"
						>
							<el-input
								v-model.trim="dialog.formData.templateName"
								style="width:80%"
								:maxlength="10"
								:placeholder="$t('common.please_enter')"
							></el-input>
						</el-form-item>
						<el-form-item
							:label="$t('agent.template_desc') + ':'"
							prop="templateDes"
						>
							<el-input
								v-model.trim="dialog.formData.templateDes"
								type="textarea"
								:maxlength="500"
								show-word-limit
								:placeholder="$t('common.please_enter')"
								style="width:80%"
							></el-input>
						</el-form-item>
					</el-form>
					<span slot="footer">
						<el-button @click="dialog.visible = false">
							{{ $t('common.cancel') }}
						</el-button>
						<el-button
							type="primary"
							:disabled="dialog.disabled"
							@click="handleCreateOrEdit"
						>
							<i
								v-show="dialog.disabled"
								class="el-icon-loading"
							></i>
							<span>{{ $t('common.sure') }}</span>
						</el-button>
					</span>
				</el-dialog>

				<!-- 分页 -->
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</div>
		</div>
	</div>
	<Settings
		v-else
		:settings-data="settingsData"
		:pageType.sync="pageType"
		@loadData="loadData"
	></Settings>
</template>

<script>
// 结合自己的UI,名称和功能、函数等
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import { filterEmptyParams } from '@/utils'
const startTime = dayjs()
	.startOf('day')
	.valueOf()
const endTime = dayjs()
	.endOf('day')
	.valueOf()

export default {
	name: routerNames.contractTemplate,
	components: {
		Settings: () => import('./components/Settings.vue')
	},
	mixins: [list],
	data() {
		// this.loadData = this.throttle(this.loadData, 1000)
		// this._changeTableSort = this.throttle(this._changeTableSort, 1000)
		return {
			queryData: {
				policyTypeConfigId: undefined
			},
			selectSearchVal: [startTime, endTime],
			selectSearchVal2: '',
			selectSearchType: 1,
			selectSearchType2: 1,
			createdAt: [startTime, endTime],
			updatedAt: [],
			tableData: [],
			typeConfigIdList: [],
			dialogTypeConfigIdList: [],
			cloneTypeConfigIdList: [],
			contractType: '',
			pageType: 'i',
			dialog: {
				title: undefined,
				visible: false,
				disabled: false,
				formData: {
					templateType: undefined,
					templateName: undefined,
					policyTypeConfigId: undefined,
					templateDes: undefined,
					merchantId: undefined
				},
				rules: {
					merchantId: [
						{
							required: true,
							message: this.$t('agent.rule_select_tip_merchant'),
							trigger: 'blur'
						}
					],
					templateName: [
						{
							required: true,
							message: this.$t('agent.rule_input_tip_template'),
							trigger: 'blur'
						}
					],
					templateType: [
						{
							required: true,
							message: this.$t('agent.rule_select_tip_template'),
							trigger: 'change'
						}
					],
					policyTypeConfigId: [
						{
							required: true,
							message: this.$t(
								'agent.rule_select_tip_policy_type'
							),
							trigger: 'change'
						}
					],
					templateDes: [
						{
							required: true,
							message: this.$t('agent.rule_desc_tip'),
							trigger: 'blur'
						},
						{
							min: 2,
							max: 500,
							message: this.$t('agent.rule_length_tip2-500'),
							trigger: 'blur'
						}
					]
				}
			},
			settingsData: {}
		}
	},
	computed: {
		templateTypeArr() {
			return this.globalDics.contractTemplateType || []
		},
		accountTypeArr() {
			return this.globalDics.accountType || []
		}
	},
	created() {},

	mounted() {
		this.getPolicyTypeOnSearchForm(this.contractType, true)
	},
	methods: {
		refresh() {
			this.getPolicyTypeOnSearchForm(this.contractType, true)
			this.loadData()
		},
		selectSearchType2Handle() {
			this.selectSearchVal2 = ''
		},
		selectMerchantHandle(merchantId) {
			this.getPolicyTypeInDialog(this.contractType, false, merchantId)
		},
		getPolicyType(val, arr, init = false, merchantId) {
			const params = { contractType: val }
			if (merchantId) {
				params.merchantId = merchantId
			}
			this.$api.getProxyMinContractPolicyTypeList(params).then((res) => {
				if (res?.code === 200) {
					this[arr] = res.data || []
					// this[arr].push({
					// 	id: 0,
					// 	policyType: this.$t('agent.custom')
					// })
					if (init) {
						this.cloneTypeConfigIdList = JSON.parse(
							JSON.stringify(res.data)
						)
					}
				}
			})
		},
		getPolicyTypeInDialog(val, init = false, merchantId) {
			if (
				this.dialog.formData.policyTypeConfigId ||
				this.dialog.formData.policyTypeConfigId === 0
			) {
				this.dialog.formData.policyTypeConfigId = undefined
			}
			const _merchantId = merchantId || this.dialog.formData.merchantId
			this.getPolicyType(val, 'dialogTypeConfigIdList', init, _merchantId)
		},
		getPolicyTypeOnSearchForm(val, init = false) {
			if (
				this.queryData.policyTypeConfigId ||
				this.queryData.policyTypeConfigId === 0
			) {
				this.queryData.policyTypeConfigId = undefined
			}
			this.getPolicyType(
				val,
				'typeConfigIdList',
				init,
				this.queryData.merchantId
			)
		},
		filterPolicyType(policyTypeConfigId, contractType) {
			const currentPolicyType = this.cloneTypeConfigIdList?.find(
				(item) =>
					item.id === policyTypeConfigId &&
					item.contractType === contractType
			)
			return currentPolicyType?.policyType
				? currentPolicyType.policyType
				: '-'
		},
		loadData() {
			this.loading = true
			delete this.queryData.createdStartTime
			delete this.queryData.createdEndTime
			delete this.queryData.updatedStartTime
			delete this.queryData.updatedEndTime
			delete this.queryData.createdBy
			delete this.queryData.updatedBy
			if (this.selectSearchVal) {
				if (this.selectSearchType === 1) {
					const [createdStartTime, createdEndTime] =
						this.selectSearchVal || []
					this.queryData.createdStartTime = dayjs(
						createdStartTime
					).format('YYYY-MM-DD HH:mm:ss')
					this.queryData.createdEndTime = dayjs(
						createdEndTime
					).format('YYYY-MM-DD HH:mm:ss')
				} else if (this.selectSearchType === 2) {
					const [updatedStartTime, updatedEndTime] =
						this.selectSearchVal || []
					this.queryData.updatedStartTime = dayjs(
						updatedStartTime
					).format('YYYY-MM-DD HH:mm:ss')
					this.queryData.updatedEndTime = dayjs(
						updatedEndTime
					).format('YYYY-MM-DD HH:mm:ss')
				}
			}

			if (this.selectSearchType2 === 1) {
				this.queryData.createdBy = this.selectSearchVal2
			} else if (this.selectSearchType2 === 2) {
				this.queryData.updatedBy = this.selectSearchVal2
			}

			let params = {
				...this.queryData
			}
			params = {
				...this.getParams(params)
			}

			this.$api
				.getContractTemplateListAPI(filterEmptyParams(params))
				.then((res) => {
					if (res?.code === 200) {
						const { records, total } = res.data || {}
						this.tableData = Array.isArray(records)
							? Object.freeze(records)
							: []
						this.total = total || 0
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		filterContractType(val) {
			const res = this.templateTypeArr.find(
				(item) => item.code === String(val)
			)
			return res?.description || '-'
		},
		reset() {
			this.queryData = {
				policyTypeConfigId: undefined
			}
			this.selectSearchType = 1
			this.selectSearchType2 = 1
			this.selectSearchVal2 = ''
			this.createdAt = [startTime, endTime]
			this.selectSearchVal = [startTime, endTime]
			this.updatedAt = []
			this.pageNum = 1
			this.getPolicyTypeOnSearchForm('', true)
			this.loadData()
		},
		_changeTableSort({ column, prop, order }) {
			if (prop === 'loginTime') {
				prop = 1
			}
			this.pageNum = 1
			this.queryData.orderKey = prop
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		openDialog(isEdit, rowData) {
			this.getPolicyTypeInDialog(this.contractType)
			this.dialog.visible = true
			if (isEdit) {
				this.dialog.title = this.$t('common.edit')
				const {
					id,
					templateName,
					templateType,
					policyTypeConfigId,
					templateDes,
					merchantId
				} = rowData
				this.dialog.formData = Object.assign(
					{},
					{
						id,
						templateName,
						policyTypeConfigId,
						templateType: String(templateType),
						templateDes,
						merchantId
					}
				)
			} else {
				this.dialog.title = this.$t('common.create')
				this.dialog.formData = {
					templateName: undefined,
					templateType: '',
					templateDes: undefined,
					merchantId: undefined
				}
				if (this.merchantList.length === 1) {
					this.dialog.formData.merchantId = this.merchantList[0]['id']
				}
			}
			this.$nextTick(() => {
				this.$refs['dialogForm'].clearValidate()
			})
		},
		handleCreateOrEdit() {
			this.$refs.dialogForm.validate((valid) => {
				if (valid) {
					this.dialog.disabled = true
					const apiName =
						this.dialog.title === this.$t('common.edit')
							? 'editContractTemplateAPI'
							: 'addContractTemplateAPI'
					const params = {
						...this.dialog.formData
					}

					this.$api[apiName](params)
						.then((res) => {
							this.$message.success(
								this.dialog.title + this.$t('agent.success')
							)
							this.refresh()
							// this.loadData()
							this.dialog.disabled = false
							this.dialog.visible = false
						})
						.catch(() => {
							this.dialog.disabled = false
						})
				}
			})
		},
		closeDialog() {
			this.$refs['dialogForm'].clearValidate()
		},
		openSettings(rowData) {
			this.pageType = 's'
			this.settingsData = Object.assign({}, rowData)
			this.settingsData.policyType = this.typeConfigIdList.find(
				(item) => item.id === rowData.policyTypeConfigId
			)
		},
		del(rowData, index) {
			this.$confirm(`${this.$t('agent.confirm_delete')}?`, {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			})
				.then(() => {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.5)'
					})
					this.$api
						.delContractTemplateApi({ id: rowData.id })
						.then((res) => {
							this.$message({
								type: 'success',
								message: this.$t('agent.delete_success')
							})
							loading.close()
							this.loadData()
						})
						.catch(() => {
							loading.close()
						})
				})
				.catch(() => {})
		},
		back() {
			this.pageType = 'i'
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
	border-bottom: 1px solid #00000015;
}
::v-deep .tagheight .el-tag {
	height: 24px;
	line-height: 24px;
	min-width: 60px;
}
.msgList {
	font-size: 14px;
	display: flex;
	p {
		margin-right: 20px;
		line-height: 24px;
	}
	&:last-child p {
		margin-bottom: 15px;
	}
}
::v-deep .el-input-group__prepend {
	background-color: #fff;
}
</style>
